<script setup lang="ts">
/**
 * @name ReportCenterEnergyConsumingUnit
 * @description 用能单元统计
 */

import dayjs from 'dayjs'
import { Download, List } from '@element-plus/icons-vue'
import type { DatePickType } from 'element-plus'
import { useEnergyConsumingUnit } from '@/mixins/ReportCenter/MixinEnergyConsumingUnit'
import { STORAGE_MODES } from '@/enum/modules/indicator'
import { useSimpleExportLists } from '@/components/TableLists/useSimpleExportLists'
import XLSX from 'xlsx-js-style'

import type { Point } from '@/components/ReadonlyPointTree/ReadonlyPointTree'

const [point, setPoint] = useState<Point | null>(null)
const {
  loading,
  columns,
  tableData,
  sortByAscending,
  sortByDescending,
  getEnergyConsumingUnitData,
} = useEnergyConsumingUnit()
const reportType = ref(STORAGE_MODES.DAY)
const [time1] = useState(dayjs().format('YYYY-MM-DD'))
const [time2] = useState(dayjs().format('YYYY-MM'))
const [time3] = useState(dayjs().format('YYYY'))

const pickerType = computed<DatePickType>(() => {
  switch (reportType.value) {
    case STORAGE_MODES.DAY:
      return 'date'
    case STORAGE_MODES.MONTH:
      return 'month'
    case STORAGE_MODES.YEAR:
      return 'year'
    default:
      return 'date'
  }
})
const pickerFormatter = computed(() => {
  switch (reportType.value) {
    case STORAGE_MODES.DAY:
      return 'YYYY-MM-DD'
    case STORAGE_MODES.MONTH:
      return 'YYYY-MM'
    case STORAGE_MODES.YEAR:
      return 'YYYY'
    default:
      return 'YYYY-MM-DD'
  }
})
const tableCaption = computed(() => {
  switch (reportType.value) {
    case STORAGE_MODES.DAY:
      return '能耗统计日报'
    case STORAGE_MODES.MONTH:
      return '能耗统计月报'
    case STORAGE_MODES.YEAR:
      return '能耗统计年报'
    default:
      return '能耗统计日报'
  }
})
const time = computed(() => {
  switch (reportType.value) {
    case STORAGE_MODES.DAY:
      return time1.value
    case STORAGE_MODES.MONTH:
      return time2.value
    case STORAGE_MODES.YEAR:
      return time3.value
    default:
      return time1.value
  }
})

function handleClickNode(o: Point) {
  setPoint(o)
}
function clickSearch() {
  const pointId = unref(point)?.id
  const t = unref(time)
  if (pointId && t) {
    getEnergyConsumingUnitData({
      pointId,
      timeType: unref(reportType),
      time: t === 'Invalid Date' ? dayjs().format(unref(pickerFormatter)) : t,
    })
  }
}
function clickDownload() {
  const { exportXlsx } = useSimpleExportLists<any>({
    columns: unref(columns) as any,
    lists: unref(tableData),
  })

  exportXlsx(unref(tableCaption), () => {
    return [
      [{ v: unref(tableCaption), t: 's', s: {
        alignment: { horizontal: 'center', wrapText: true },
        font: { sz: 20 },
      } }],
      [
        `统计范围：${unref(point)?.pointFullName}`,
        ...Array(Math.max(unref(columns).length - 2, 0)).fill(null),
        `统计时间：${unref(time)}`,
      ],
    ]
  }, () => {
    return [
      { s: { r: 0, c: 0 }, e: { r: 0, c: Math.max(unref(columns).length - 1, 1) } },
    ]
  }, (wb, worksheet, data) => {
    // 你可以通过循环设置整列的格式
    // 获取列数（假设第一行是表头）
    const numColumns = data[0].length

    // 从第二列（B列）开始设置数值格式
    for (let col = 2; col <= numColumns; col++) { // col从2开始，跳过A列
      const colLetter = XLSX.utils.encode_col(col - 1) // 将列索引转换为列字母（如2->B, 3->C等）

      for (let row = 2; row <= data.length; row++) { // 从第二行开始处理数据
        const cellRef = `${colLetter}${row}`
        if (worksheet[cellRef]) {
          worksheet[cellRef].t = 'n' // 设置单元格类型为数字
          worksheet[cellRef].z = '0.00' // 设置为两位小数的数字格式
        }
      }
    }
  })
}
function sortChangeHandler({ prop, order }: any) {
  if (order === 'ascending') {
    sortByAscending(prop)
  }
  else {
    sortByDescending(prop)
  }
}

watch(
  [
    () => unref(point)?.id,
    () => unref(time),
  ],
  clickSearch,
)
</script>

<template>
  <div class="padding-sm flex container">
    <div class="points-container">
      <ReadonlyPointTree fire :need-full-name="1" @click-node="handleClickNode" />
    </div>
    <div class="margin-left-sm flex-fillRemaining flex flex-col overflow-auto">
      <div class="flex-shrink-0">
        <ElForm inline>
          <ElFormItem label="报表类型">
            <ElRadioGroup v-model="reportType">
              <ElRadio :value="STORAGE_MODES.DAY">
                日报
              </ElRadio>
              <ElRadio :value="STORAGE_MODES.MONTH">
                月报
              </ElRadio>
              <ElRadio :value="STORAGE_MODES.YEAR">
                年报
              </ElRadio>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem label="统计时间">
            <div v-show="reportType === STORAGE_MODES.DAY">
              <ElDatePicker
                v-model="time1"
                :type="pickerType"
                placeholder="选择日期"
                :value-format="pickerFormatter"
                :format="pickerFormatter"
                :clearable="false"
                :editable="false"
              />
            </div>
            <div v-show="reportType === STORAGE_MODES.MONTH">
              <ElDatePicker
                v-model="time2"
                :type="pickerType"
                placeholder="选择月份"
                :value-format="pickerFormatter"
                :format="pickerFormatter"
                :clearable="false"
                :editable="false"
              />
            </div>
            <div v-show="reportType === STORAGE_MODES.YEAR">
              <ElDatePicker
                v-model="time3"
                :type="pickerType"
                placeholder="选择年份"
                :value-format="pickerFormatter"
                :format="pickerFormatter"
                :clearable="false"
                :editable="false"
              />
            </div>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" :icon="List" @click="clickSearch">
              统计
            </ElButton>
            <ElButton type="success" :icon="Download" @click="clickDownload">
              导出
            </ElButton>
          </ElFormItem>
        </ElForm>
      </div>
      <h3 class="m-0 text-center">
        {{ tableCaption }}
      </h3>
      <div
        class="flex items-center py-3"
        style="
          font-size: var(--el-font-size-base);
          color: var(--el-text-color-regular);
        "
      >
        <span class="text-truncate">统计范围：{{ point?.pointFullName }}</span>
        <span class="ml-auto text-truncate">统计时间：{{ time }}</span>
      </div>
      <div class="alpha-block flex-1 overflow-auto p-[10px]">
        <ElTable
          v-loading="loading" element-loading-custom-class="global-loading"
          :data="tableData"
          height="100%"
          show-summary
          @sort-change="sortChangeHandler"
        >
          <template #empty>
            <TableEmpty />
          </template>
          <ElTableColumn
            v-for="(column, index) in columns"
            :key="index"
            :label="column.label" :prop="column.prop"
            :sort-orders="['ascending', 'descending']"
            sortable="custom"
          />
        </ElTable>
      </div>
    </div>
  </div>
</template>
